<template>
  <div class="wrapper">
    <el-form :model="classLook"
      ref="ruleForm">
      <el-form-item label="升级规则：">
        <el-checkbox-group v-model="checkList"
          :min="1">
          <el-checkbox label="1">消费间夜</el-checkbox>
          <el-checkbox label="2">累计积分</el-checkbox>
          <el-checkbox label="3">付费直升</el-checkbox>
        </el-checkbox-group>
        <p style="font-size:12px;margin-left:70px">会员升级条件可自主配置，会员只需满足以其中任意一条即可升级。</p>
      </el-form-item>

      <el-form-item label="等级设置：">
        <table>
          <tr class="style">
            <th>会员等级({{classLook.classSets.length}}/10)</th>
            <th>等级名称</th>
            <th v-if="checkList.indexOf('1')>-1">消费间夜成长值</th>
            <th v-if="checkList.indexOf('2')>-1">累计积分成长值</th>
            <th v-if="checkList.indexOf('3')>-1">付费直升</th>
            <th>背景图片
              <p>图片建议尺寸：500* 300像素，大小不超过1MB</p>
            </th>
          </tr>
          <tr v-for="(item,index) in classLook.classSets"
            :key="index">
            <td>{{index+1}}</td>
            <td style="text-align: left;">
              <el-form-item :prop="'classSets.'+index+ '.name'"
                :rules="{
                  required: true, message: '等级名称', trigger: 'blur'
                }">
                <el-input placeholder="请输入等级名称"
                  maxlength="10"
                  style="width:200px"
                  v-model="item.name"></el-input>
              </el-form-item>
            </td>
            <td class="clearfix"
              v-if="checkList.indexOf('1')>-1">
              <el-form-item class="fl"
                :prop="'classSets.'+index+ '.upNight'"
                :rules="{
                  required: true, message: '请输入消费间夜成长值', trigger: 'blur'
              }">
                <el-input-number v-model="item.upNight"
                  controls-position="right"
                  style="width:150px"
                  :disabled="index===0"
                  size="small"
                  :precision="0"
                  :max="!index? 0: 2000000"
                  :min="!index? 0 :1"></el-input-number>
              </el-form-item>
            </td>
            <td class="clearfix"
              v-if="checkList.indexOf('2')>-1">
              <el-form-item class="fl"
                :prop="'classSets.'+index+ '.upIntegral'"
                :rules="{
                  required: true, message: '请输入积分成长值', trigger: 'blur'
              }">
                <el-input-number v-model="item.upIntegral"
                  controls-position="right"
                  style="width:150px"
                  class="fl"
                  size="small"
                  :disabled="index===0"
                  :max="!index? 0: 2000000"
                  :min="!index? 0 :1"
                  :precision="0"></el-input-number>
              </el-form-item>
            </td>
            <td v-if="checkList.indexOf('3')>-1"
              style="width:180px">
              <el-form-item class="fl"
                :prop="'classSets.'+index+ '.upPay'"
                :rules="{
                  required: true, message: '请输入付费直升金额', trigger: 'blur'
               }">
                <span class="fl">￥&nbsp;&nbsp;</span>
                <el-input-number v-model="item.upPay"
                  class="fl"
                  size="small"
                  controls-position="right"
                  :precision="0"
                  :disabled="index===0"
                  :max="!index? 0: 2000000"
                  :min="!index? 0 :1"
                  style="width:150px"></el-input-number>
              </el-form-item>
            </td>
            <td style="padding:25px">
              <el-form-item class="fl"
                :ref="'img'+index"
                :prop="'classSets.'+index+ '.imgMin'"
                :rules="{
                  required: true, message: '请选择背景图片',trigger: 'trigger'
               }">
                <el-upload class="avatar-uploader"
                  :before-upload="beforeAvatarUpload"
                  style="max-height:150px;overflow:hidden"
                  :show-file-list="false"
                  :http-request="sendChange"
                  action="https://jsonplaceholder.typicode.com/posts/">
                  <i class="el-icon-plus avatar-uploader-icon"
                    v-if="!item.imgMin"  @click="handleIndex(index)"></i>
                  <img :src="item.imgMin"  @click="handleIndex(index)"
                    style="width:250px;height:150px"
                    v-if="item.imgMin"
                    alt="背景图片">
                </el-upload>
              </el-form-item>
            </td>
          </tr>
        </table>
      </el-form-item>
      <el-form-item label-width="70px">
        <el-button type="primary"
          size="small"
          @click="addLevel('ruleForm')">增添等级</el-button>
        <el-button type="primary"
          size="small"
          @click="_delete"
          :disabled="classLook.classSets.length==1">删除等级</el-button>
      </el-form-item>
    </el-form>
    <div>
      <InfomationBtns v-has="'memberclassredact'">
        <el-button size="small"
          type="primary"
          @click="sure('ruleForm')">保存</el-button>
        <el-button size="small"
          type="primary"
          @click="next('ruleForm')">下一步</el-button>
      </InfomationBtns>
    </div>
  </div>
</template>

<script>
import { upimg } from "@/public/js/setting";
import InfomationBtns from "@/components/common/InfomationBtns";
import {
  getMemberCardLevel,
  deleteMemberLevel,
  setMemberLevel
} from "@/public/js/member";
export default {
  components: {
    InfomationBtns
  },
  props: ["toggleFn"],
  data() {
    return {
      openNight: 1,
      openPay: 2,
      openIntegral: 2,
      index: 0,
      checkList: [],
      classLook: { classSets: [] }
    };
  },
  watch: {
    classLook:{
      handler(classLook){
        classLook.classSets[0].upIntegral = 0;
        classLook.classSets[0].upNight = 0;
        classLook.classSets[0].upPay = 0;
      },
      deep:true
    }
  },
  computed: {},
  methods: {
    //获取会员卡等级
    _getMemberCardLevel() {
      getMemberCardLevel().then(res => {
        let data = res.data.classLook
          ? res.data.classLook
          : {
              classSets: [
                {
                  id: "",
                  name: "",
                  upNight: 0,
                  upIntegral: 0,
                  upPay: 0,
                  imgMin: "",
                  classNum: 1
                }
              ],
              openNight: 1,
              openIntegral: 2,
              openPay: 2
            };

        data.classSets.map(item => {
          Object.keys(item).forEach(function(key) {
            item[key] = item[key] == null ? undefined : item[key];
          });
        });
        this.classLook = data;
        this.openNight = data.openNight;
        this.openPay = data.openPay;
        this.openIntegral = data.openIntegral;
        this.checkList = [];
        //格式化数据
        if (this.openNight == 1) {
          this.checkList.push("1");
        }
        if (this.openIntegral == 1) {
          this.checkList.push("2");
        }
        if (this.openPay == 1) {
          this.checkList.push("3");
        }
      });
    },

    // 增添等级
    addLevel(formName) {
      if (this.classLook.classSets.length === 10) {
        this.$message.error("最多只能创建10个等级会员卡");
        return false;
      }
      //表单验证
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.classLook.classSets.push({
            id: "",
            name: "",
            upNight: undefined,
            upIntegral: undefined,
            upPay: undefined,
            imgMin: "",
            classNum: this.classLook.classSets.length + 1
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //上传图片
    sendChange(e) {
      var reader = new FileReader();
      reader.readAsDataURL(e.file);
      reader.onload = e => {
        let photoPath = e.target.result;
        upimg({
          nowPath: photoPath,
          oldPath: this.classLook.classSets[this.index].imgMin
        }).then(res => {
          this.classLook.classSets[this.index].imgMin = res.data.path;
          let ref = "img" + this.index;
          this.$refs[ref][0].clearValidate();
        });
      };
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error("上传头像只能是 JPG/PNG 格式的图片!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    //删除
    _delete() {
      let id = this.classLook.classSets[this.classLook.classSets.length - 1].id;
      if (id) {
        this.$confirm("是否继续该删除操作?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deleteMemberLevel({ id }).then(res => {
            if (!res.data.errCode) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.classLook.classSets.splice(
                this.classLook.classSets.length - 1
              );
            }
          });
        });
      } else {
        this.classLook.classSets.splice(this.classLook.classSets.length - 1);
      }
    },
    //保存
    sure(formName) {
      this._sure(formName, 1);
    },
    //下一步
    next(formName) {
      this._sure(formName);
    },
    //保存数据
    _sure(formName, type) {
      //表单验证
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.openNight = 2;
          this.openPay = 2;
          this.openIntegral = 2;
          this.checkList.forEach(item => {
            if (item == "1") {
              this.openNight = 1;
            }
            if (item == "3") {
              this.openPay = 1;
            }
            if (item == "2") {
              this.openIntegral = 1;
            }
          });
          setMemberLevel({
            openNight: this.openNight,
            openPay: this.openPay,
            openIntegral: this.openIntegral,
            classSets: this.classLook.classSets
          }).then(res => {
            if (!res.data.errCode) {
              if (type) {
                this.$message({
                  type: "success",
                  message: "操作成功"
                });
              } else {
                this.toggleFn();
              }
              this._getMemberCardLevel();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleIndex(index) {
      this.index = index;
    }
  },
  created() {
    this._getMemberCardLevel();
  },
  mounted() {
    // console.log(this.$refs.wrap.offsetWidth)
    this.width = this.$refs.ruleForm.offsetWidth + 55 + "px";
  }
};
</script>
<style lang="scss" scoped>
.wrapper {
  padding-bottom:80px;
  table {
    border-collapse: collapse;
    text-align: center;
    min-width: 1200px;
  }
  tr {
    .require {
      color: red;
      font-size: 16px;
      display: inline-block;
      line-height: 16px;
    }
  }
  tr.style {
    background: #f2f2f2;
  }
  table td,
  table th {
    border: 1px solid #cad9ea;
    color: #666;
    width: auto;
    padding: 0 5px;
    font-size: 12px;
    height: 40px;

    &.style {
      background: #f2f2f2;
    }
  }
}
</style>